import React from 'react';
import { useState, useEffect } from 'react'
import type { FC } from 'react';
import './patientDetail.css'
import { Image } from 'antd-mobile'
import HomeHeader from '../../compontent/header'
import { useNavigate, useSearchParams } from 'react-router-dom'
import request from '../../api/axios'
import video from '../../../public/Icon/video_n.png'
import home from '../../../public/Icon/home_s.png'
import editIcon from '../../../public/Icon/patient_support_group_issue.png'

const PatientDetail: FC = ({ }) => {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const [detailData, setDetailData] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [showOverlay, setShowOverlay] = useState(false)
  const [overlayType, setOverlayType] = useState<'likes' | 'comments' | 'collect' | 'dislikes'>('likes')
  const [commentText, setCommentText] = useState('')
  const [showCommentInput, setShowCommentInput] = useState(false)
  const [commentList, setCommentList] = useState<any[]>([])
  const [commentLoading, setCommentLoading] = useState(false)
  const [commentPage, setCommentPage] = useState(1)
  const [hasMoreComments, setHasMoreComments] = useState(true)
  const [submittingComment, setSubmittingComment] = useState(false)

  // 时间格式化函数
  const formatDateTime = (dateTime: string) => {
    if (!dateTime) return { date: '', time: '' };
    const date = new Date(dateTime);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return {
      date: `${year}-${month}-${day}`,
      time: `${hours}:${minutes}`
    };
  };

  // 处理stat-icon点击事件
  const handleStatClick = (type: 'likes' | 'comments' | 'collect' | 'dislikes') => {
    setOverlayType(type)
    setShowOverlay(true)

    // 如果是评论类型，加载评论数据
    if (type === 'comments') {
      getCommentList(1, true)
    }
  }

  // 关闭遮罩层
  const closeOverlay = () => {
    setShowOverlay(false)
    setShowCommentInput(false)
    setCommentText('')
  }

  // 显示评论输入框
  const showCommentInputHandler = () => {
    setShowCommentInput(true)
  }

  // 隐藏评论输入框
  const hideCommentInput = () => {
    setShowCommentInput(false)
    setCommentText('')
  }

  // 提交评论
  const submitComment = async () => {
    if (commentText.trim() && detailData?.sickCircleId && !submittingComment) {
      try {
        setSubmittingComment(true)

        // 从本地存储获取用户信息
        const user = JSON.parse(localStorage.getItem('user') || '{}')

        // 调用发表评论API
        const response = await request.post(`/api/health/user/sickCircle/verify/v1/publishComment?sickCircleId=${Number(detailData.sickCircleId)}&content=${commentText.trim()}`,
          new URLSearchParams({
            sickCircleId: detailData.sickCircleId.toString(),
            content: commentText.trim()
          }),
          {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              userId: user.userId || '',
              sessionId: user.sessionId || ''
            }
          }
        )

        if (response?.data?.code === 200) {
          // 提交成功
          setCommentText('')
          setShowCommentInput(false)
          // 刷新评论列表
          await getCommentList(1, true)
          console.log('评论提交成功')
        } else {
          console.error('评论提交失败:', response?.data?.message)
        }
      } catch (error) {
        console.error('提交评论失败:', error)
      } finally {
        setSubmittingComment(false)
      }
    }
  }

  // 处理输入框变化
  const handleCommentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setCommentText(e.target.value)
  }

  // 获取评论列表
  const getCommentList = async (page: number = 1, isRefresh: boolean = false) => {
    if (!detailData?.sickCircleId) return

    try {
      setCommentLoading(true)

      // 从本地存储获取用户信息
      const user = JSON.parse(localStorage.getItem('user') || '{}')

      const token = localStorage.getItem('token') || ''

      const response = await request.get('/api/health/user/sickCircle/v1/findSickCircleCommentList', {
        params: {
          sickCircleId: detailData.sickCircleId,
          page: page,
          count: 10
        },
        headers: {
          userId: user.userId || '',
          sessionId: token
        }
      })

      const newComments = response?.data?.result || []

      if (isRefresh) {
        setCommentList(newComments)
      } else {
        setCommentList(prev => [...prev, ...newComments])
      }

      // 判断是否还有更多数据
      setHasMoreComments(newComments.length === 10)
      setCommentPage(page)

    } catch (error) {
      console.error('获取评论列表失败:', error)
    } finally {
      setCommentLoading(false)
    }
  }

  const getDetailData = async () => {
    try {
      setLoading(true)
      const sickCircleId = searchParams.get('id')
      if (!sickCircleId) {
        navigate('/patient')
        return
      }

      // 从本地存储获取用户信息
      const user = JSON.parse(localStorage.getItem('user') || '{}')
      const token = localStorage.getItem('token') || ''

      const response = await request.get(`/api/health/user/sickCircle/v1/findSickCircleInfo`, {
        params: { sickCircleId },
        headers: {
          userId: user.id || '',
          sessionId: token
        }
      })

      setDetailData(response?.data?.result || null)
    } catch (error) {
      console.error('获取详情失败:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    getDetailData()
  }, [searchParams]);

  if (loading) {
    return (
      <div className="patient">
        <header className="patient-header">
          <HomeHeader></HomeHeader>
        </header>
        <div className="patient-main">
          <div className="loading">加载中...</div>
        </div>
      </div>
    )
  }

  if (!detailData) {
    return (
      <div className="patient">
        <header className="patient-header">
          <HomeHeader></HomeHeader>
        </header>
        <div className="patient-main">
          <div className="error">数据加载失败</div>
        </div>
      </div>
    )
  }

  return (
    <div className="patient">
      <header className="patient-header">
        <HomeHeader></HomeHeader>
      </header>
      <div className="patient-main">
        <div className="patientDetail-container">
          {/* 标题区域 */}
          <div className="patientDetail-header">
            <div className="patientDetail-title">{detailData.title}</div>
            <div className="patientDetail-time">{formatDateTime(detailData.releaseTime).date} {formatDateTime(detailData.releaseTime).time}</div>
          </div>

          {/* 用户信息 */}
          <div className="patientDetail-user">
            <div className="patientDetail-avatar">
              {detailData.headPic ? (
                <Image src={detailData.headPic} width={50} height={50} />
              ) : (
                <div className="avatar-placeholder">👤</div>
              )}
            </div>
            <div className="patientDetail-user-info">
              <div className="patientDetail-username">{detailData.nickName || '匿名用户'}</div>
              <div className="patientDetail-disease">[病症] {detailData.disease}</div>
              <div className="patientDetail-department">[科室] {detailData.department}</div>
            </div>
          </div>

          {/* 病症详情 */}
          <div className="patientDetail-section">
            <div className="patientDetail-section-title">[病症详情]</div>
            <div className="patientDetail-content">{detailData.detail}</div>
          </div>

          {/* 治疗经历 */}
          <div className="patientDetail-section">
            <div className="patientDetail-section-title">[治疗经历]</div>
            <div className="patientDetail-treatment">
              <div className="treatment-hospital">医院：{detailData.treatmentHospital}</div>
              <div className="treatment-time">
                治疗时间：{detailData.treatmentStartTime} - {detailData.treatmentEndTime}
              </div>
              <div className="treatment-process">{detailData.treatmentProcess}</div>
            </div>
          </div>

          {/* 相关图片 */}
          {detailData.picture && (
            <div className="patientDetail-section">
              <div className="patientDetail-section-title">[相关图片]</div>
              <div className="patientDetail-images">
                <Image src={detailData.picture} width="100%" height="200px" />
              </div>
            </div>
          )}

          {/* 统计信息 */}
          <div className="patientDetail-stats">
            <div className="stat-item">
              <span className="stat-icon">⭐</span>
              <span className="stat-text">{detailData.collectionNum || 0}</span>
            </div>
            <div className="stat-item" onClick={() => handleStatClick('comments')}>
              <span className="stat-icon">💬</span>
              <span className="stat-text">{detailData.commentNum || 0}</span>
            </div>

          </div>

          {/* 被采纳的建议 */}
          {detailData.adoptFlag === 1 && detailData.adoptComment && (
            <div className="patientDetail-adopt">
              <div className="patientDetail-section-title">[被采纳的建议]</div>
              <div className="adopt-suggestion">
                <div className="adopt-user">
                  <div className="adopt-avatar">
                    <Image src={detailData.adoptHeadPic} width={40} height={40} />
                  </div>
                  <div className="adopt-user-info">
                    <div className="adopt-username">{detailData.adoptNickName}</div>
                    <div className="adopt-reward">获得20H币</div>
                    <div className="adopt-time">{formatDateTime(detailData.adoptTime).date}</div>
                  </div>
                </div>
                <div className="adopt-content">{detailData.adoptComment}</div>
              </div>
            </div>
          )}
        </div>
      </div>
      <footer className="patient-footer">
        <div className="tab" onClick={() => navigate('/')}>
          <div className="tab-icon" style={{ textAlign: "center" }}><Image src={home} width={24} height={24}></Image></div>
          <div className="tab-label">首页</div>
        </div>
        <div className="center-btn" onClick={() => navigate('/patient')}>
          <div className="center-inner"><Image src={editIcon}></Image></div>
        </div>
        <div className="tab" onClick={() => navigate('/my')}>
          <div className="tab-icon" style={{ textAlign: "center" }}><Image src={video} width={24} height={24}></Image></div>
          <div className="tab-label">视频</div>
        </div>
      </footer>

      {/* 遮罩层 */}
      {showOverlay && (
        <div className="overlay" onClick={closeOverlay}>
          <div className="overlay-content" onClick={(e) => e.stopPropagation()}>
            <div className="overlay-header">
              <h3 className="overlay-title">
                {overlayType === 'comments' && '评论用户'}
              </h3>
              <button className="close-btn" onClick={closeOverlay}>×</button>
            </div>
            <div className="overlay-body">
              {overlayType === 'likes' && (
                <div className="user-list">
                  <div className="no-data">暂无点赞用户</div>
                </div>
              )}
              {overlayType === 'dislikes' && (
                <div className="user-list">
                  <div className="no-data">暂无踩的用户</div>
                </div>
              )}
              {overlayType === 'collect' && (
                <div className="user-list">
                  <div className="no-data">暂无收藏用户</div>
                </div>
              )}
              {
                <div className="comment-list">
                  {commentLoading && commentList.length === 0 ? (
                    <div className="loading-comments">加载中...</div>
                  ) : commentList.length > 0 ? (
                    commentList.map((comment, index) => (
                      <div key={comment.id || index} className="comment-item">
                        <div className="comment-avatar">
                          {comment.headPic ? (
                            <Image src={comment.headPic} width={40} height={40} />
                          ) : (
                            '👤'
                          )}
                        </div>
                        <div className="comment-content">
                          <div className="comment-header">
                            <span className="comment-name">{comment.nickName || '匿名用户'}</span>
                            <span className="comment-time">{formatDateTime(comment.createTime).date} {formatDateTime(comment.createTime).time}</span>
                          </div>
                          <div className="comment-text">{comment.content}</div>
                          <div className="comment-actions">
                            <span className="comment-like">👍 {comment.likeNum || 0}</span>
                            <span className="comment-dislike">👎 {comment.dislikeNum || 0}</span>
                          </div>
                        </div>
                      </div>
                    ))
                  ) : (
                    <div className="no-comments">暂无评论</div>
                  )}

                  {/* 加载更多按钮 */}
                  {commentList.length > 0 && hasMoreComments && (
                    <div className="load-more-comments">
                      <button
                        className="load-more-btn"
                        onClick={() => getCommentList(commentPage + 1, false)}
                        disabled={commentLoading}
                      >
                        {commentLoading ? '加载中...' : '加载更多'}
                      </button>
                    </div>
                  )}
                </div>
              }
            </div>

            {/* 评论输入栏 - 只在评论类型时显示 */}
            {overlayType === 'comments' && (
              <div className="comment-input-bar">
                <button className="comment-close-btn" onClick={hideCommentInput}>×</button>
                <div className="comment-input-wrapper">
                  <input
                    type="text"
                    className="comment-input"
                    placeholder="在此留下高见吧!!"
                    value={commentText}
                    onChange={handleCommentChange}
                    onFocus={() => setShowCommentInput(true)}
                    onClick={showCommentInputHandler}
                  />
                </div>
                {showCommentInput && (
                  <button
                    className={`comment-submit-btn ${submittingComment ? 'submitting' : ''}`}
                    onClick={submitComment}
                    disabled={!commentText.trim() || submittingComment}
                  >
                    {submittingComment ? '发送中...' : '发送'}
                  </button>
                )}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};
export default PatientDetail;